package com.xuecheng.system.config;

import com.xuecheng.system.entity.Dictionary;
import com.xuecheng.system.entity.ex.CourseCategoryNodes;
import com.xuecheng.system.mapper.CourseCategoryMapper;
import com.xuecheng.system.service.CourseCategoryService;
import com.xuecheng.system.service.DictionaryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.List;

@Component
public class RedisInit implements ApplicationRunner {
    @Autowired
    private RedisTemplate<String, Serializable> serializableRedisTemplate;

    @Autowired
    private DictionaryService dictionaryService;

    @Autowired
    private CourseCategoryService courseCategoryService;

    @Autowired
    private CourseCategoryMapper categoryMapper;

    /**
     * 初始化redis缓存存入课程分类和字典数据
     *
     * @param args
     * @throws Exception
     */
    public void run(ApplicationArguments args) throws Exception {

        //先判断redis中是否有数据
        if(!(serializableRedisTemplate.hasKey("dictionary001"))){
            //1.查询字典数据，
            List<Dictionary> list = dictionaryService.list();

            //2.遍历集合使用hash存储到redis中
            for (Dictionary dictionary : list) {

                serializableRedisTemplate.opsForHash().put("dictionary001",dictionary.getId(),dictionary);
            }

        }


        if (!(serializableRedisTemplate.hasKey("courseNodes001"))){
            //1.查询类型数据，
            List<CourseCategoryNodes> result = categoryMapper.queryAll();

            //2.遍历集合使用hash存储到redis中
            for (CourseCategoryNodes categoryNodes : result) {
                serializableRedisTemplate.opsForHash().put("courseNodes001",categoryNodes.getId(),categoryNodes);
            }
        }


    }
}
